import time
from selenium.webdriver.support.select import Select
from selenium.webdriver import ActionChains
from selenium.webdriver.support.wait import WebDriverWait

from config import PATH


class BasePage(object):
    def __init__(self, driver):
        self.driver = driver

    def fd_element(self, loc):
        try:
            element = WebDriverWait(self.driver, 10).until(lambda x: x.find_element(*loc))
            return element
        except Exception as e:
            print("元素定位失败：{}".format(e))
            raise

    def get_shot(self, file_name):
        """
        截图
        :param file_name: 截图文件名
        :return:无
        """
        # self.driver.get_screenshot_as_file(PATH + r"\img\pwd_error.png")
        self.driver.get_screenshot_as_file(PATH + '/img/' + file_name)

    def base_input(self, loc, text):
        """
        输入框输入公共方法
        :param loc: 元素定位方式及属性值
        :param text: 输入内容
        :return: 无
        """
        # self.fd_element(loc).clear()
        # self.fd_element(loc).send_keys(text)
        # 定位元素
        ele = self.fd_element(loc)
        # 清空输入框
        ele.clear()
        # 输入内容
        ele.send_keys(text)

    def base_click(self, loc):
        """
        点击公共方法
        :param loc: 元素定位方式及属性值
        :return: 无
        """
        self.fd_element(loc).click()

    def get_handles(self, loc):
        """
        切换多窗口并获取指定元素
        :param loc: 定位的元素信息
        :return: 第二个窗口的页面元素
        """
        time.sleep(3)
        handles = self.driver.window_handles
        self.driver.switch_to.window(handles[1])
        element = self.fd_element(loc)
        return element

    def base_switch_frame(self, loc):
        """
        切换frame
        :param loc: frame的定位信息
        :return: 无
        """
        frame_ele = self.fd_element(loc)
        self.driver.switch_to.frame(frame_ele)

    def base_default_frame(self):
        """
        切换到默认frame
        :return: 无
        """
        self.driver.switch_to.default_content()

    def action_move(self, loc):
        """
        鼠标悬停
        """
        action = ActionChains(self.driver)
        action.move_to_element(self.fd_element(loc)).perform()

    def select_click(self, loc, text):
        """
        下拉框选择
        """
        ele = Select(self.fd_element(loc))
        ele.select_by_value(text)
